<?php
class Api_Select_Product extends Zend_Db_Table_Select
{
    const FILTER_ALL = 0;
    const FILTER_NEW = 1;
    const FILTER_DISCOUNT = 2;
    const FILTER_AVAL = 3;

    const SORT_NO = 0;
    const SORT_CODE = 1;
    const SORT_NAME = 2;
    const SORT_PRICE = 3;
    const SORT_AUTHOR = 4;
    const SORT_SIZE = 5;

    public function filter($filter)
    {
        $filter = ( int )$filter;
        switch ($filter) {
            case self::FILTER_ALL :
                return $this;
            case self::FILTER_NEW :
                return $this->where('`p`.`is_new` = ?', true);
            case self::FILTER_DISCOUNT :
                return $this->where('`p`.`is_discount` = ?', true);
            case self::FILTER_AVAL :
                return $this->where('`a`.`quantity` = ?', false);
                $this->from('`a`=>`quantity`');
        }
        return $this;
    }

    public function all()
    {
        $this->from(array('p' => 'products'))->setIntegrityCheck(false);

        return $this->join(array('pr' => 'prices'), '`p`.`id` = `pr`.`product_id`', array('price_1', 'price_2'))->join(array('a' => 'available'), '`p`.`id` = `a`.`product_id`', array('quantity'));
    }

    public function search($str)
    {
        return $result = (!( int )$str) ? $this->where('`p`.`name` LIKE ?', "%" . $str . "%")
                : $this->where('`p`.`code` = ?', $str);
    }

    public function sort($type, $is_asc = true)
    {
        $type = ( int )$type;
        $order = $is_asc ? self::SQL_ASC : self::SQL_DESC;
        switch ($type) {
            case self::SORT_NO :
                return $this;
            case self::SORT_CODE :
                return $this->order('code ' . $order);

            case self::SORT_AUTHOR :
                return $this->order('authors_name ' . $order);
            case self::SORT_SIZE :
                return $this->order('size ' . $order);

            case self::SORT_NAME :
                return $this->order('name ' . $order);
            case self::SORT_PRICE :
                {
                $usr = Zend_Registry::get('Core_User');
                //				if($usr->isGuest()) return $this;
                return $this->order('price ' . $order);
                }
        }
    }

    public function author( $AuthorId )
    {
        return $this -> where( '`ap`.`author_id` = ?', $AuthorId );

    }
}